//
//  VideoPlayerVC.m
//  echo
//
//  Created by dllo on 16/2/27.
//  Copyright © 2016年 Danny. All rights reserved.
//

#define WIDTH [UIScreen mainScreen].bounds.size.width / 414
#define HEIGHT [UIScreen mainScreen].bounds.size.height / 736

#import "VideoPlayerVC.h"
#import <AVFoundation/AVFoundation.h>
#import "ModelForVideoPlayer.h"
#import "ModelOfCellForMyExploreTableViewSectionOne.h"
#import <DKNightVersion/DKNightVersion.h>

@interface VideoPlayerVC ()
@property (nonatomic, retain)UIView *backView;
@property (nonatomic, retain)UIView *progressView;
@property (nonatomic, assign)BOOL isPlay;
@property (nonatomic, retain)AVPlayerItem *playItem;
@property (nonatomic, retain)AVPlayerLayer *playLayer;
@property (nonatomic, retain)AVPlayer *player;
@property (nonatomic, assign)BOOL isHidden;
@property (nonatomic, retain)UISlider *slider;
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, retain)UIButton *buttonForBack;
@property (nonatomic, retain)UILabel *labelForTime;
@property (nonatomic, assign)CGFloat videoTime;
@property (nonatomic, retain)ModelForVideoPlayer *modelForData;
@end

@implementation VideoPlayerVC

- (void)dealloc{
    [_backView release];
    [_progressView release];
    [_playItem release];
    [_playLayer release];
    [_player release];
    [_slider release];
    [_button release];
    [_buttonForBack release];
    [_labelForTime release];
    [_modelForData release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.isPlay = YES;
    self.isHidden = NO;
    
    [self createViews];
    [self createVideoPlayer];
    [self createTapGesture];
    [self settingUpSlider];
}

- (void)createViews{
    self.navigationController.navigationBarHidden = YES;
    self.backView = [[UIView alloc]initWithFrame:self.view.frame];
    self.backView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.backView];
    [self.backView release];
    
    self.progressView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 245 * HEIGHT, self.view.frame.size.width, 40 * HEIGHT)];
    [self.backView addSubview:self.progressView];
    self.progressView.backgroundColor = [UIColor colorWithRed:232/255.f green:76/255.f blue:84/255.f alpha:1];
    [self.progressView release];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(5 * WIDTH, 0, 40 * WIDTH, 40 * WIDTH);
    [self.progressView addSubview:self.button];
    [self.button release];
    [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(5 * WIDTH + 40 * WIDTH + 5 * WIDTH, 0, 245 * WIDTH, 40 * HEIGHT)];
    [self.progressView addSubview:self.slider];
    [self.slider addTarget:self action:@selector(handleSlider:) forControlEvents:UIControlEventValueChanged];
    
    self.labelForTime = [[UILabel alloc]initWithFrame:CGRectMake(5 * WIDTH + 40 * WIDTH + 5 * WIDTH + 250 * WIDTH + 5 * WIDTH, 0, 110 * WIDTH, 40 * HEIGHT)];
    [self.progressView addSubview:self.labelForTime];
    [self.labelForTime release];
    
    self.buttonForBack = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonForBack.frame = CGRectMake(7 * WIDTH, 30 * HEIGHT, 40 * WIDTH, 35 * HEIGHT);
    [self.backView addSubview:self.buttonForBack];
    [self.buttonForBack setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    self.navigationItem.hidesBackButton = YES;
    [self.buttonForBack addTarget:self action:@selector(handleBackForVideo) forControlEvents:UIControlEventTouchUpInside];
}

- (void)handleBackForVideo{
    [self.player pause];
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)createVideoPlayer{

    NSString *url = [NSString stringWithString:self.modelForData.urlForMusic];
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *urlOfVideo = [NSURL URLWithString:url];
    
    self.playItem = [[AVPlayerItem alloc]initWithURL:urlOfVideo];
    self.player = [AVPlayer playerWithPlayerItem:self.playItem];
    [self.player replaceCurrentItemWithPlayerItem:self.playItem];
    [self.playItem release];
    
    self.playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playLayer.frame = self.backView.frame;
    self.playLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    
    [self.backView.layer insertSublayer:self.playLayer atIndex:0];
    
    
    [self.player play];
    
}

- (void)createTapGesture{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handletap)];
    
    [self.view addGestureRecognizer:tap];
    
    
}

- (void)handletap{
    
    if (self.isHidden == NO) {
        
        [UIView animateWithDuration:0.5 animations:^{
            self.progressView.alpha = 1;
            self.buttonForBack.hidden = NO;
        }];
    }else{

        [UIView animateWithDuration:0.5 animations:^{
            
            self.progressView.alpha = 0;
            
            self.buttonForBack.hidden = YES;
        }];
    }
    self.isHidden = !self.isHidden;
}

- (void)settingUpSlider{
    
    __block VideoPlayerVC *vc = self;
    [vc.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        CGFloat duration = CMTimeGetSeconds(self.playItem.duration);
        CGFloat current = CMTimeGetSeconds(self.playItem.currentTime);
        
        NSString *totalTime = [NSString stringWithFormat:@"%.2d:%.2d", (int)duration/60, (int)duration%60];
        NSString *currentTime = [NSString stringWithFormat:@"%.2d:%.2d", (int)current/60, (int)current%60];
        
        NSString *timeOfLabel = [NSString stringWithFormat:@"%@/%@", currentTime,totalTime];
        self.labelForTime.text = timeOfLabel;
        
        self.slider.value = current / duration;
        
        self.videoTime = duration;
    }];
}

- (void)handleButton:(UIButton *)button{
    if (self.isPlay == YES) {
        [self.player pause];
        
        [self.button setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
        
    }else{
        
        
        [self.player play];
        [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        
    };
    self.isPlay = !self.isPlay;
}

- (void)handleSlider:(UISlider *)slider{
    double currentTime = self.videoTime * self.slider.value;
    CMTime toTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:toTime completionHandler:^(BOOL finished) {
        [self.player play];
        [self.button setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    }];
}

- (void)passModelForMyExploreVC:(ModelOfCellForMyExploreTableViewSectionOne *)model{
    self.modelForData = [[ModelForVideoPlayer alloc]init];
    self.modelForData.urlForMusic = model.source;
}

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    self.backView.dk_backgroundColorPicker = DKColorWithColors([UIColor blackColor], [UIColor blackColor]);
    self.progressView.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:232/255.f green:76/255.f blue:84/255.f alpha:1], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.player pause];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
